<?php
/**
 * 消息队列服务
 * Created by PhpStorm.
 */

namespace app\service;

use app\common\lib\MsgQueue;
use app\models\business\FileLogModel;

class MessageQueue
{
    /**
     * 接受消息回调
     * @param $queueName
     * @param string $data
     * @return bool
     * @date 2020-08-03 16:57
     */
    public function receiveCallBack($queueName, $data = [])
    {
        $result = false;
        try {
            switch ($queueName) {
                case MsgQueue::QUEUE_NORMAL: //普通消息
                    $this->normalQueueCallback($data);
                    $result = true;
                    break;
                case MsgQueue::QUEUE_OUTAPI_ACCESSLOG: //外部接口日志
                    $res = $this->outApiAccessLog($data);
                    $result = true;
                    break;
                case MsgQueue::QUEUE_FILE_UPLOAD: //文件上传
                    $res = $this->fileUpload($data);
                    $result = true;
                    break;
                case MsgQueue::QUEUE_RESPONSE_LOG: //请求响应日志
                    $res = $this->responseLog($data);
                    $result = true;
                    break;
                case MsgQueue::QUEUE_FILE_UPLOAD: //文件上传
                    $this->fileUpload($data);
                    $result = true;
                    break;
                default:
                    break;
            }
        } catch (\Exception $e) {
            //dump($e->getMessage());
            $result = false;
        }
        return $result;
    }

    /**
     * 接收延时队列消息回调
     * @param $queueName
     * @param array $data
     * @return array
     * @date 2021-06-16 18:06
     */
    public function receiveDelayCallBack($queueName, $data = [])
    {
        try {
            switch ($queueName) {
                case MsgQueue::QUEUE_DELAY_NORMAL: //普通延迟消息
                    $res = $this->normalDelayQueueCallback($data);
                    if (in_array($res['status'], [STATUS_CODE_SUCCESS, STATUS_CODE_NOTFOUND, STATUS_CODE_DATAERROR])) {
                        return funReturn(STATUS_CODE_SUCCESS, 'success');
                    }
                    return funReturn(STATUS_CODE_INSIDEERROR, 'success', ['delaySecond' => $res['data']['delaySecond'] ?? 10]);
                    break;
                default:
                    break;
            }
        } catch (\Exception $e) {

            return funReturn(STATUS_CODE_INSIDEERROR, 'error', $e->getMessage(), ['delaySecond' => 10]);
        }
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }

    /**
     * Note:普通消息回调测试
     * User:端木凌风
     * Date:2021-09-06 14:04
     */
    private function normalQueueCallback($data)
    {
        echo "\e[32mNowTime\e[0m:" . date("Y-m-d H:i:s") . "\n";
        echo "\e[32mMessageType\e[0m:normal\n";
        echo "\e[33m传递的数据:\e[0m\n";
        dump($data);
    }

    /**
     * Note:普通延迟消息回调测试
     * User:端木凌风
     * Date:2021-09-06 14:08
     */
    private function normalDelayQueueCallback($data)
    {
        echo "\e[32mNowTime\e[0m:" . date("Y-m-d H:i:s") . "\n";
        echo "\e[32mMessageType\e[0m:delay\n";
        echo "\e[33m传递的数据:\e[0m\n";
        dump($data);
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }

    /**
     * Note:http请求响应日志
     * User:端木凌风
     * Date:2022-11-25 15:46
     * @param $data
     * @return array
     */
    private function responseLog($data)
    {
        $obj = new \app\models\common\ResponseLogModel();
        $obj->createRecord($data);
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }

    /**
     * 外部系统接口日志
     * @param $data
     * @return array
     * @date 2020-08-11 18:21
     */
    private function outApiAccessLog($data)
    {
        $obj = new \app\models\common\OutApiAccessLogModel();
        $client_id = $data['client_id'] ?? 0;
        $request_url = $data['request_url'] ?? '';
        $request_data = $data['data'] ?? '';
        $request_time = $data['request_time'] ?? date('Y-m-d H:i:s');
        $response_data = $data['response_data'] ?? '';
        $response_code = $data['response_code'] ?? '';
        $request_type = $data['request_type'] ?? '';
        $obj->createRecord($client_id, $request_url, $request_data, [
            'request_time' => $request_time,
            'response_data' => $response_data,
            'response_code' => $response_code,
            'request_type' => $request_type
        ]);
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }

    /**
     * 文件创建后回调
     * @param array $data
     * @return array
     */
    public function fileUpload($data = [])
    {
        $param = [
            'api_key' => $data['api_key'] ?? '',
            'file_time' => $data['file_time'] ?? '',
        ];
        $obj = new  FileLogModel();
        $saveFile = $data['save_file'] ?? '';
        $originFile = $data['origin_file'] ?? '';
        if ($saveFile) {
            $saveData = $param;
            $saveData['file_path'] = $data['save_file'];
            $res = $obj->createRecord($saveData);
        }
        if ($originFile and $originFile != $saveFile) {
            $saveData = $param;
            $saveData['file_path'] = $data['origin_file'];
            $res = $obj->createRecord($saveData);
        }
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }


    /**
     * Note:计算延迟时间
     * User:端木凌风
     * Date:2021-09-06 15:08
     * @param $notifyTimes
     * @return float|int
     */
    private function createDelaySecond($notifyTimes)
    {
        $delaySecond = 1;
        $maxRetryCount = 10;
        $step = intval($maxRetryCount / 3);
        if ($notifyTimes <= $step) {
            $delaySecond = ($notifyTimes - 1) * 10 + 10;
        } else if ($notifyTimes > $step && $notifyTimes <= 2 * $step) {
            $delaySecond = ($notifyTimes - 1) * 300;
        } else {
            $delaySecond = ($notifyTimes - 1) * 3600;
        }
        return $delaySecond;
    }
}
